#/usr/bin/python3
# coding=utf-8

import json
import sys
sys.path.append("..")
sys.path.append(".")
sys.dont_write_bytecode = True

import requests
from utils.logger_helpper import logger

class RequestUtil:
    def __init__(self, base_url, default_headers=None, timeout=None):
        self.base_url = base_url
        self.default_headers = default_headers or {'Content-Type': 'application/json'}
        self.timeout = timeout or 60
        self.session = requests.Session()

    def send_request(self, method, endpoint, params=None, data=None, json=None, headers=None, **kwargs):
        """
        发送HTTP请求
        :param method: 请求方法 (get/post/put/delete)
        :param url: 请求URL
        :param params: 查询参数
        :param data: 表单数据
        :param json: JSON数据
        :param headers: 请求头
        :param kwargs: 其他requests参数
        :return: 响应对象
        """
        method = method.lower()
        url = f"{self.base_url}{endpoint}"
        req_headers = headers if headers else self.default_headers
        logger.info(f"请求URL:{url}")
        logger.info(f"请求Method: {method.upper()}")
        logger.info(f"请求Header: {req_headers}")
        logger.info(f"请求Params: {params}")
        logger.info(f"请求Data: {data}")

        try:
            if method == 'get':
                response = self.session.get(url, params=params, data=data, json=json, headers=req_headers, **kwargs)
            elif method == 'post':
                response = self.session.post(url, params=params, data=data, json=json, headers=req_headers, **kwargs)
            elif method == 'put':
                response = self.session.put(url,  params=params, data=data, json=json, headers=req_headers, **kwargs)
            elif method == 'delete':
                response = self.session.delete(url, params=params, data=data, json=json, headers=req_headers, **kwargs)
            else:
                raise ValueError(f"不支持的请求方法: {method}")

            logger.debug(f"响应内容: {response.json()}")
            return response
        except Exception as e:
            logger.error(f"请求发生异常: {str(e)}")
            raise
